package esiag.pds.contextManagement;

import java.io.Serializable;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

import com.edu.message.MessageInOut;
import com.esiag.pdsteam.gestion.InformationInOut;

import javolution.util.FastList;
import esiag.pds.PoolThread.MyThreadPool;
import esiag.pds.beans.Parameters;
import esiag.pds.interfaces.IContextProvider;
import esiag.pds.interfaces.IgetContext;

public class ContextManager  extends UnicastRemoteObject implements IgetContext  {

	 public static Logger log = Logger.getLogger("log_file");
	 FileHandler hand;
	
	private Context context;
	private MyThreadPool poolOfThread;
	IContextProvider s;
	
	public ContextManager(Parameters param) throws RemoteException {
		
		context =new Context();
		poolOfThread=new MyThreadPool(param.getMin(),param.getMax(),param.getAliveTime()
										,param.getBlockingQueue());
				
		//Logger
		try {
			hand = new FileHandler("MonLog.txt");
			log.addHandler(hand);
			SimpleFormatter formatter=new SimpleFormatter();
			hand.setFormatter(formatter);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			}
		s=(IContextProvider)InformationInOut.getNewInstance();
	}
	

	public Context getContext() throws RemoteException {
		return poolOfThread.doWork(context);
		//return context;
	}
	
	public void upDateContext(){
	//	System.out.println("<< Server side : The context was upDated >>");
		log.info("<< Server side : The context was upDated >>\n"+
				"Context FastLists count : "+ context.getNbList());
	//	System.out.println("Context FastLists count : "+ context.getNbList());
		if(s!=null){
			context.set(s.getContext());
		}
	}
	
	public void setContextProvider(IContextProvider s){
		this.s=s;
	}
	
	public void addList(FastList<Serializable>list){
		context.addList(list);
	}
	
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return context.toString();
	}
	
	public void setContext(Context context){
		this.context=context;
	}

}
